package com.xh.filepicker.sdk.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xh.filepicker.sdk.R;
import com.xh.filepicker.sdk.models.Config;
import com.xh.filepicker.sdk.models.DirectoryModel;
import com.xh.filepicker.sdk.utils.TextHighlighter;
import com.xh.filepicker.sdk.utils.Utils;

import java.util.ArrayList;


/**
 * Created by zhuangshaobo on 2021/6/15.
 */
public class DirectoryAdapter extends RecyclerView.Adapter<DirectoryAdapter.ViewHolder> implements Filterable {

    private Context context;
    private ArrayList<DirectoryModel> filesList;
    private ArrayList<DirectoryModel> filesListFiltered;
    private onFilesClickListener onFilesClickListener;
    private ArrayList<String> selected;
    private Config config;
    private String keyword;

    @Override
    public Filter getFilter() {
        return tempFilter;
    }

    private Filter tempFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            ArrayList<DirectoryModel> filteredList = new ArrayList<>();
            if (constraint == null || constraint.length() == 0) {
                filteredList = filesList;
                keyword = "";
            } else {
                String filteredPattern = constraint.toString().toLowerCase().trim();
                keyword = filteredPattern;
                for (DirectoryModel model : filesList) {
                    if (model.getName().toLowerCase().contains(filteredPattern)) {
                        filteredList.add(model);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filesListFiltered = (ArrayList<DirectoryModel>) results.values;
            notifyDataSetChanged();
        }
    };


    public interface onFilesClickListener {
        void onClicked(DirectoryModel model);
        void onFileSelected(DirectoryModel fileModel);
    }

    public void setDataList(ArrayList<DirectoryModel> list) {
        this.filesListFiltered = list;
        notifyDataSetChanged();
    }

    public DirectoryAdapter(Context context, ArrayList<DirectoryModel> list, onFilesClickListener onFilesClickListener) {
        this.context = context;
        this.filesList = list;
        this.filesListFiltered = list;
        this.onFilesClickListener = onFilesClickListener;
        this.selected = new ArrayList<>();
        this.config = Config.getInstance();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (viewType == 1) {
            view = LayoutInflater.from(context).inflate(R.layout.fp_file_picker_item_directory, parent, false);
        } else {
            view = LayoutInflater.from(context).inflate(R.layout.fp_file_picker_item_file, parent, false);
        }
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        TextHighlighter textHighlighter = new TextHighlighter()
//                .setBackgroundColor(Color.parseColor("#FFFF00")) //匹配文本的背景色
                .setForegroundColor(context.getResources().getColor(R.color.fp_text_highlight)); //匹配文本的颜色
//                .setBold(true) //粗体
//                .setItalic(true) //斜体

        final DirectoryModel item = filesListFiltered.get(position);
        if (item.isDirectory()) {
            holder.tv_folder_name.setText(item.getName());
            holder.tv_num_files.setText("文件：" + item.getNum_files());

            if (!TextUtils.isEmpty(keyword)) {
                textHighlighter.addTarget(holder.tv_folder_name)
                        .highlight(keyword, TextHighlighter.CASE_INSENSITIVE_MATCHER);
            }
        } else {
            changeFileIcon(holder, item.getName());
            holder.tv_file_name.setText(item.getName());
            holder.tv_file_size.setText(Utils.byte2FitMemorySize(item.getSize(), 1));
            holder.tv_date.setText(Utils.longToReadableDate(item.getLast_modif_time()));

            if (!TextUtils.isEmpty(keyword)) {
                textHighlighter.addTarget(holder.tv_file_name)
                        .highlight(keyword, TextHighlighter.CASE_INSENSITIVE_MATCHER);
            }
        }
        if (!config.showOnlyDirectory() && item.isDirectory()) {
            holder.view_divider.setVisibility(View.GONE);
            holder.cb_selected.setVisibility(View.GONE);
            holder.btn_selected.setVisibility(View.GONE);
        } else {
            holder.view_divider.setVisibility(View.VISIBLE);
            holder.cb_selected.setVisibility(View.VISIBLE);
            holder.btn_selected.setVisibility(View.VISIBLE);
        }
        final String path = item.getPath();
        holder.cb_selected.setChecked(selected.contains(path));
        holder.btn_selected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (config.isSelectMultiple()) {
                    if (config.getSelectMaxNum() > 0 && config.getSelectMaxNum() == selected.size()) {
                        Toast.makeText(context, "最多只能选择"+config.getSelectMaxNum()+"个文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (selected.contains(path)) {
                        selected.remove(path);
                    } else {
                        selected.add(path);
                    }
                } else {
                    /* if selection is empty, add the current item */
                    if (selected.size()==0) {
                        selected.add(0, path);
                    }
                    /* if item already selected then remove it */
                    else if (selected.get(0).equals(path)) {
                        selected.remove(0);
                    }
                    /* if another item selected, then remove and then add current item */
                    else{
                        selected.remove(0);
                        selected.add(0, path);
                    }
                }
                notifyDataSetChanged();
                onFilesClickListener.onFileSelected(filesListFiltered.get(position));
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (item.isDirectory()) {
                    onFilesClickListener.onClicked(filesListFiltered.get(position));
                } else {
                    Utils.openFile(context, item.getPath());
                }
            }
        });
    }

    private void changeFileIcon(ViewHolder holder, String fileName) {
       try{
           String extension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
           if (extension.contains("apk")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_apk);
           } else if(extension.contains("doc") || extension.contains("docx")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_doc);
           } else if(extension.contains("html")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_h5);
           } else if(extension.contains("jpg") || extension.contains("jpeg") || extension.contains("png")
                   || extension.contains("gif") || extension.contains("bmp")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_image);
           } else if(extension.contains("mp3") || extension.contains("flac") || extension.contains("ape")
                   || extension.contains("aac") || extension.contains("ogg") || extension.contains("wav")
                   || extension.contains("wma") || extension.contains("amr") || extension.contains("awb")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_music);
           } else if(extension.contains("pdf")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_pdf);
           } else if(extension.contains("ppt") || extension.contains("pptx")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_ppt);
           } else if(extension.contains("rar") || extension.contains("zip") || extension.contains("7z")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_rar);
           } else if(extension.contains("txt")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_txt);
           } else if(extension.contains("mp4") || extension.contains("mkv") || extension.contains("avi")
                   || extension.contains("wmv") || extension.contains("webm") || extension.contains("3gp")
                   || extension.contains("asf")) {
               holder.item_icon.setImageResource(R.drawable.fp_ic_file_video);
           }
       }catch (Exception e){
           holder.item_icon.setImageResource(R.drawable.fp_ic_file_unknown);
       }
    }

    /**
     * resets the value of selected so that UI gets updated
     */
    public void resetSelection() {
        this.selected = new ArrayList<>();
    }

    @Override
    public int getItemViewType(int position) {
        if (filesListFiltered.get(position).isDirectory()) {
            return 1;
        } else {
            return 2;
        }
    }

    @Override
    public int getItemCount() {
        return filesListFiltered.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView tv_folder_name;
        TextView tv_num_files;
        TextView tv_file_name;
        TextView tv_file_size;
        TextView tv_date;
        View view_divider;
        CheckBox cb_selected;
        Button btn_selected;
        ImageView item_icon;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_folder_name = itemView.findViewById(R.id.tv_folder_name);
            tv_num_files = itemView.findViewById(R.id.tv_num_files);
            tv_file_name = itemView.findViewById(R.id.tv_file_name);
            tv_file_size = itemView.findViewById(R.id.tv_file_size);
            tv_date = itemView.findViewById(R.id.tv_date);
            view_divider = itemView.findViewById(R.id.view_divider);
            cb_selected = itemView.findViewById(R.id.cb_select);
            btn_selected = itemView.findViewById(R.id.btn_select);
            item_icon = itemView.findViewById(R.id.iv_icon);
        }
    }
}
